//
//  HDAdressPickerView.m
//  AccountEasy
//
//  Created by 黄志刚 on 2020/8/14.
//  Copyright © 2020 AccountEasy. All rights reserved.
//

#import "HDAdressPickerView.h"
#import "HDAdressProvinceModel.h"
#import "HDAdressCityModel.h"
#import "NSArray+HDsafe.h"
#import "HDPermanentAddressListAPI.h"

@interface HDAdressPickerView ()<UIPickerViewDelegate,UIPickerViewDataSource,HTTPAPIDelegate>
// pickerview  创建
@property (nonatomic ,strong)UIView *toolsView;
@property (nonatomic ,strong)UIPickerView *pickerView;

/** 当前省数组 */
@property (strong, nonatomic) NSMutableArray<HDAdressProvinceModel *> *provinceArray;
/** 当前城市数组 */
@property (strong, nonatomic) NSArray<HDAdressCityModel *> *cityArray;
/** 当前地区数组 */
@property (strong, nonatomic) NSArray<HDAdressDistrictModel *> *districtArray;
@property (nonatomic,assign) NSInteger provinceIndex;//省索引
@property (nonatomic,assign) NSInteger cityIndex;//城市索引
/** 当前选中地址 */
@property (strong, nonatomic) HDAdressModel *selectedAdress;
@property (strong, nonatomic) HDPermanentAddressListAPI *permanentAddressListAPI;

@end

@implementation HDAdressPickerView

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    self.provinceArray = [HDAdressProvinceModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        self.cityArray = self.provinceArray.firstObject.city_list;
    [self.pickerView reloadAllComponents];//重新加载数据
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

/**
 初始化
 
 @param title 地址选择框标题
 @param selectedLocation 回调方法
 */
- (instancetype)initWithTitle:(NSString *)title  slectedLocation:(SelectedLocation)selectedLocation{
    if (self = [super init]){
        self.titleString = title;
        if ([title isEqualToString:@"选择常住地"]) {
            self.isNetWork = YES; //对 HDPayContentVC 选择页面进行单独处理，后台未优化造成
        }
        self.selectedLocation  = selectedLocation;
        [self setupUI];
        [self loadData];
    }
    return self;
}

#pragma mark - Private Methods
- (void)setupUI{
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.backgroundColor =colorHexA(0x000000, 0.0);
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    }];
    
    _toolsView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(250), kScreenWidth, kScaleNum(55))];
    _toolsView.backgroundColor = colorHex(0xF7F8F9);
    _toolsView.layer.cornerRadius = 5;
    _toolsView.layer.masksToBounds = YES;
    [self addSubview:_toolsView];
    
    // 右边确定按钮
    UIButton *rightSureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightSureBtn.frame = SARectMake(kBaseScreenWidth - 60, 0, 60, 44);
    [rightSureBtn setTitle:@"确定" forState:UIControlStateNormal];
    rightSureBtn.titleLabel.font = kFont(15);
    [rightSureBtn setTitleColor:colorHex(0x3B9BFF) forState:UIControlStateNormal];
    [rightSureBtn addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_toolsView addSubview:rightSureBtn];
    
    // 中间显示  label
    if (self.titleString.length > 0) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:SARectMake(54, 0, kBaseScreenWidth - 108, 44)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = self.titleString;
        titleLabel.font = kFont(15);
        [_toolsView addSubview:titleLabel];
    }
    
    // 左边取消按钮
    UIButton *leftCancleButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftCancleButton.frame = CGRectMake(0, 0, 60, 44);
    [leftCancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [leftCancleButton setTitleColor:colorHex(0xA5AEB7) forState:UIControlStateNormal];
    leftCancleButton.titleLabel.font = kFont(15);
    [leftCancleButton addTarget:self action:@selector(leftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_toolsView addSubview:leftCancleButton];
    
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(202), kScreenWidth, kScaleNum(202))];
    _pickerView.dataSource = self;
    _pickerView.delegate = self;
    [_pickerView selectRow:0 inComponent:0 animated:YES];
    _pickerView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_pickerView];
}
- (void)loadData
{
    if (self.isNetWork == YES) {
        [self.permanentAddressListAPI sendRequestToServerWithActivityViewAndMask:POST];
        return;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"bankcitylist" ofType:@"json"];
    NSError *error;
    NSString *jsonString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        return;
    }
    NSData  * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError * error2;
    NSArray * provinces = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error2];
    for (NSDictionary *dic in provinces) {
        HDAdressProvinceModel *province = [[HDAdressProvinceModel alloc] initWithDictionary:dic];
        [self.provinceArray addObject:province];
    }
    //默认选中第一个
    self.cityArray = self.provinceArray.firstObject.city_list;
}
//左边按钮(取消)
- (void)leftButtonClick:(UIButton *)button{
    [self dismiss];
}
//  右边按钮 (确认)
- (void)rightButtonClick:(UIButton *)button{
    if (self.selectedLocation){
        self.selectedLocation(self.selectedAdress);
    }
    [self dismiss];
}
//屏幕点击事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismiss];
}
//消失的方法
- (void)dismiss{
    __weak typeof (self)weakSelf = self;
    __weak typeof(UIView *)blockView = _toolsView;
    __weak typeof(UIPickerView *)blockPickerViwe = _pickerView;
    [UIView animateWithDuration:0.3 animations:^{
        blockView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScaleNum(44));
        blockPickerViwe.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScaleNum(200));
    }completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}
#pragma mark - System Delegate
#pragma mark -  数据源方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.provinceArray.count;
    } else if (component == 1) {
        return self.cityArray.count;
    }
    return 0;
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return kScaleNum(44);
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return [self.provinceArray objectAtIndex:row].bank_area;
    } else if (component == 1) {
        return [self.cityArray objectAtIndex:row].bank_city;
    }
    return @"";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.provinceIndex = row;
        HDAdressProvinceModel *province = [self.provinceArray hd_safeObjectAtIndex:row];
        self.cityArray = province.city_list;
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
    }
    if (component == 1) {
        self.cityIndex = row;
    }
}

//重写方法
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:kFont(15)];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
    
}
/**
 显示PickerView
 */
- (void)show{
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
}

#pragma mark - Getter or Setter
- (NSMutableArray<HDAdressProvinceModel *> *)provinceArray{
    if (_provinceArray == nil) {
        _provinceArray = [NSMutableArray array];
    }
    return _provinceArray;
}
- (HDAdressModel *)selectedAdress{
    HDAdressProvinceModel *province = [self.provinceArray hd_safeObjectAtIndex:self.provinceIndex];
    HDAdressCityModel *city = [province.city_list hd_safeObjectAtIndex:self.cityIndex];
    HDAdressModel *adress = [[HDAdressModel alloc] init];
    adress.bank_area = province.bank_area;
    adress.bank_area_code = province.bank_area_code;
    adress.bank_city_code = city.bank_city_code;
    adress.bank_city = city.bank_city;
    return adress;
}

-(HDPermanentAddressListAPI *)permanentAddressListAPI {
    if (!_permanentAddressListAPI) {
        _permanentAddressListAPI = [HDPermanentAddressListAPI apiWithDelegate:self];
    }
    return _permanentAddressListAPI;
}

@end
